package com.mxnavi.smartd.coreui.utils;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ：zhong.jw
 * @date ：Created in 2022/5/19 11:26
 */
public class StickyLiveData<T> extends MutableLiveData<T> {

    private final AtomicInteger mGlobalVersion = new AtomicInteger(0);

    private final AtomicBoolean mStickyFlag = new AtomicBoolean(true);

    public StickyLiveData(T t) {
        super(t);
    }

    public StickyLiveData() {
        super();
    }

    @Override
    public void setValue(T value) {
        mGlobalVersion.incrementAndGet();
        super.setValue(value);
    }

    public void postValue(T value, boolean sticky) {
        setSticky(sticky);
        super.postValue(value);
    }

    @Override
    public void postValue(T value) {
        setSticky(true);
        super.postValue(value);
    }

    @Override
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
        super.observe(owner, new ObserverWrap(observer, mGlobalVersion.get()));
    }


    /**
     * 设置此liveData是否sticky
     */
    public void setSticky(boolean sticky) {
        mStickyFlag.set(sticky);
    }


    private class ObserverWrap implements Observer<T> {

        private int mVersion;

        private final Observer<? super T> mObserver;

        public ObserverWrap(Observer<? super T> observer, int version) {
            this.mObserver = observer;
            this.mVersion = version;
        }

        @Override
        public void onChanged(T t) {
            if (mGlobalVersion.get() == mVersion && !StickyLiveData.this.mStickyFlag.get()) {
                return;
            }

            mObserver.onChanged(t);
            mVersion = mGlobalVersion.get();
        }
    }
}
